package com.mz.ozy.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import androidx.core.content.FileProvider;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * apk下载安装
 *
 * @author liucan on 2019/10/15 0015.
 */
public class DownloadApkUtlis implements Runnable {

    //字节大小，K,M,G
    public static final long KB = 1024;
    public static final long MB = KB * 1024;

    private ProgressDialog dialog;
    private Context context;

    private String updatePath;
    FileOutputStream fos;
    InputStream is;
    public DownloadApkUtlis(Context context, ProgressDialog dialog, String updatePath) {
        this.dialog = dialog;
        this.context = context;
        this.updatePath = updatePath;
    }

    @Override

    public void run() {
        OkHttpClient client = new OkHttpClient();
        String url = updatePath;
        Request request = new Request.Builder().get().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                Log.d("apk状态==>", "开始下载apk");
                //获取内容总长度
                long contentLength = response.body().contentLength();
                //设置最大值
                dialog.setMax((int) contentLength);
                dialog.setProgressNumberFormat("");
                //保存到sd卡
                File apkFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".apk");
                fos = new FileOutputStream(apkFile);
                //获得输入流
                is = response.body().byteStream();
                //定义缓冲区大小
                byte[] bys = new byte[1024];
                int progress = 0;
                int len = -1;
                while ((len = is.read(bys)) != -1) {
                    try {
                        Thread.sleep(1);
                        fos.write(bys, 0, len);
                        fos.flush();
                        progress += len;
                        //设置进度
                        dialog.setProgress(progress);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
                //下载完成,提示用户安装
                installApk(apkFile);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //关闭io流
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                is = null;
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fos = null;
            }

        }
        dialog.dismiss();
    }

    private void installApk(File apkFile) {
        dialog.dismiss();
        setPermission(apkFile.getAbsolutePath());
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= 24) {
            //File file = (new File(pathstr));
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, context.getApplicationInfo().packageName + ".fileprovider", apkFile);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    //修改文件权限
    private void setPermission(String absolutePath) {
        String[] command = {"chmod", "777", absolutePath};
        ProcessBuilder builder = new ProcessBuilder(command);
        try {
            builder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
